package com.github.cyf.common.util;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;

/**
 * @author chenyifan
 * @create 2025-05-28 22:08
 */
public class ExecutorUtil {
    /**
     * 同步执行任务，主线程等待线程池执行完毕
     * @param executor 线程池
     * @param tasks 任务列表
     */
    public static void syncExecute(Executor executor, Runnable... tasks) {
        syncExecute(executor, Arrays.asList(tasks));
    }

    /**
     * 同步执行任务，主线程等待线程池执行完毕
     * @param executor 线程池
     * @param tasks 任务列表
     */
    public static void syncExecute(Executor executor, List<Runnable> tasks) {
        CountDownLatch downLatch = new CountDownLatch(tasks.size());
        for (Runnable task : tasks) {
            executor.execute(() -> {
                try {
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    downLatch.countDown();
                }
            });
        }
        try {
            downLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
